<?php

namespace App\Http\Controllers;

use App\Activity;
use App\Type;
use Illuminate\Http\Request;

class ActivityController extends Controller {
	protected $model;

	public function __construct(Activity $activity) {
		$this->model = $activity;
	}

	public function create() {
		return view('activitys.form');
	}

	public function edit(Activity $activity) {
		return view('activitys.form', compact('activity'));
	}

	public function store(Request $request) {
		$id = $request->id ?: 0;
		$this->validate($request, [
			'id' => 'sometimes|required|numeric',
			'name' => 'required|unique:activitys,name,' . $id,
			'product' => 'required',
			'days' => 'required|numeric|min:7',
			'image' => 'required',
		]);
		if ($id != 0) {
			$model = $this->model->findOrFail($id);
			$model->fill($request->only(['name', 'product', 'days', 'image']));
			$model->save();
		} else {
			$this->model->create($request->only(['name', 'product', 'days', 'image']));
		}
		return ['code' => 200, 'msg' => 'success'];
	}

	public function destroy($id) {
		$this->model->where('id', $id)->delete();
		return ['code' => 200, 'msg' => 'success'];
	}

	public function changeStatus(Request $request, $id) {
		$activity = $this->model->findOrFail($id);
		$activity->status = !$activity->status;
		$activity->save();
		return ['code' => 200, 'msg' => 'success'];
	}

	public function activitys() {
		return view('activitys.index');
	}

	public function list() {
		$activitys = $this->model->get();
		return view('activitys.list', compact('activitys'));
	}

	public function types($id) {
		echo json_encode($this->model->findOrFail($id)->load('types'));
	}

	public function map(Type $type, Request $request) {
		$this->validate($request, [
			'name' => 'required',
		]);
		$business_id = 1;
		$activity = $this->model->create(array_merge($request->only(['name']), ['business_id' => $business_id]));
		$activity->types()->attach($type->id);
		return 'success';
	}
}
